from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
# from django.utils.deprecation import MiddlewareMixin
from django.views import View

#from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置

from mydjango.settings import UPLOAD_ROOT
import os
import cv2
#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

from myapp.models import *
#导入正则
import re

# redis
import redis
# 定义IP地址和端口
host = '127.0.0.1'
port = 6379
# 定义链接对象
r = redis.Redis(host=host, port=port)

# Create your views here.

import upyun
#创建又拍云目录
class Upy(View):
    def get(self, request):
        upmkdir = request.GET.get('upmkdir')
        up = upyun.UpYun('1907md', username='fjk', password='0Fr6JYeS9L0i9RnfPNYKOFVOeH8EVQzj')
        up.mkdir('/%s/' % upmkdir)
        return HttpResponse({'message': '创建成功'})
    def delete(self,request):
        filename = request.GET.get('filename')
        up = upyun.UpYun('1907md', username='fjk', password='0Fr6JYeS9L0i9RnfPNYKOFVOeH8EVQzj')
        up.delete('/'+filename)
        return HttpResponse({'message': '删除成功'})

# 定义文件上传类
class Ypyun(APIView):
    def post(self, request):
        # 获取文件
        file = request.FILES.get('file')
        # 新建又拍云
        up = upyun.UpYun('1907md', username='fjk', password='0Fr6JYeS9L0i9RnfPNYKOFVOeH8EVQzj')
        # 声明头部信息
        headers = {'x-gmkerl-rotate': 'auto'}
        # 上传图片
        for chunk in file.chunks():
            # 又拍云路径
            res = up.put('/JWT.png', chunk, checksum=True, headers=headers)

        return Response({'filename': file.name})


# 上传
class Upload_img(APIView):
    def post(self, request):
        # 接收参数
        uid = request.POST.get('uid')
        file = request.FILES.get('file')
        print(uid, file)

        # 查询
        user = User.objects.filter(id=int(uid)).first()
        if user:
            # 建立文件流对象
            f = open(os.path.join(UPLOAD_ROOT, '', file.name), 'wb')
            # 写入
            for chunk in file.chunks():
                f.write(chunk)
                user.img = file.name
                f.close()
                # 打开
                im = Image.open('./static/upload/' + file.name)
                # 花板
                d = ImageDraw.Draw(im)
                # 修改
                d.text((180, 180), 'Django2.0.4', fill=(76, 234, 124, 180))
                # 存储图片
                im.save('./static/upload/' + file.name)
                img = cv2.imread('./static/upload/' + file.name)
                cv2.imwrite('./static/upload/1.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 5])
            user.save()
            return Response({'code': 200, 'message': '添加成功'})
        return Response({'code': 300, 'message': '添加失败'})


# 登录接口
class Login(APIView):
    def get(self, request):
        # 接收参数
        username = request.GET.get('username', None)
        password = request.GET.get('password', None)

        # 查询数据
        user = User.objects.filter(username=username, password=password).first()
        if user:
            return Response({'code': 200, 'message': '登陆成功', 'uid': user.id, 'username': user.username})
        return Response({'code': 300, 'message': '账号或密码错误'})

# 注册接口
class Reg(APIView):
    def get(self, request):
        # 接收参数
        username = request.GET.get('username', None)
        password = request.GET.get('password', None)

        # 排重操作
        user = User.objects.filter(username=username).first()
        if user:
            return Response({'code': 403, 'message': '该用户名已存在'})

        # 入库
        user = User(username=username, password=password)

        # 保存结果
        user.save()

        return Response({'code': 200, 'message': '恭喜注册成功'})

